<html>
<head>

  <script>
    let video;
    let browserType = 0;
    let controlWs;
    let sourceBuffer;
    let mediasource;
    let cnt =0;
    let bufferTime =0;
    let host = window.location.host.split(":")[0]
    let controlWsUrl = "ws:"+host+":8800"
    let videoWsUrl = "ws:"+host+":8528"

    if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1){
      browserType = 1;
    }


    function initVideo() {
      console.log("initVideo")
      video = document.querySelector('video');
      video.addEventListener("waiting", (event) => {
        console.log("Video is waiting for more data.");
      });
      video.addEventListener('durationchange', (e)=> {
        console.log("duration change")
      })
      video.addEventListener('canplay', (e)=> {
        console.log("canplay ")
      })
      video.addEventListener('timeupdate', (e)=>{
        console.log("timeupdate: " , bufferTime ,  video.currentTime,  video.readyState);
        // 缓存10秒
        if (bufferTime - video.currentTime < 10) {
          getData()
        }
      })

      let mimeCodec = 'video/mp4; codecs="avc1.64001f, mp4a.40.2"';
      if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {
        mediasource = new MediaSource();
        console.log(mediasource.readyState); // closed
        video.src = URL.createObjectURL(mediasource);
        mediasource.addEventListener('sourceopen', ()=>{
          console.log("sourceopen")
        });
      } else {
        console.error('Unsupported MIME type or codec: ', mimeCodec);
      }
    }

    function getData() {
      cnt++;
      console.log("getData", cnt)
      controlWs.send("get")
    }

   function connectVideo() {
      console.log("connectVideo")
      let ws;
      try {
        ws = new WebSocket(videoWsUrl);
        ws.binaryType = 'arraybuffer';
      } catch (e) {
        console.error(e);
        return;
      }

      ws.onopen = () => {
        console.log("video websocket open")
        getData();
        sourceBuffer = mediasource.addSourceBuffer('video/mp4; codecs="avc1.64001f, mp4a.40.2"');
        sourceBuffer.addEventListener('abort', () => {
          console.error("abort")
        });
        sourceBuffer.addEventListener('error', (e) => {
          console.error("error", e)
        });
        sourceBuffer.addEventListener('updatestart', () => {
          console.log("updatestart")
        });
        sourceBuffer.addEventListener('update', () => {
          console.log("update")
        });
        sourceBuffer.addEventListener('updateend', () => {
          console.log("updateend", mediasource.readyState, video.currentTime)
          let buffered = sourceBuffer.buffered
          console.log("readystate: " + video.readyState);
          for (let i = 0; i < buffered.length; i++) {
            console.log("buffered start: " + buffered.start(i));
            bufferTime = buffered.end(i);
            console.log("buffered end: " + buffered.end(i));
          }
          /**
           *
           * 0 = HAVE_NOTHING - 没有关于音频/视频是否就绪的信息
           1 = HAVE_METADATA - 关于音频/视频就绪的元数据
           2 = HAVE_CURRENT_DATA - 关于当前播放位置的数据是可用的，但没有足够的数据来播放下一帧/毫秒
           3 = HAVE_FUTURE_DATA - 当前及至少下一帧的数据是可用的
           4 = HAVE_ENOUGH_DATA - 可用数据足以开始播放
           * */
          if (video.readyState !== 4) {
            getData();
          }

        });
        console.log('WebSocket connected');
      };

      ws.onmessage = (event) => {
        console.log("onmessage", event.data)
        sourceBuffer.appendBuffer(event.data);
      };

      ws.onclose = () => {
        console.log('WebSocket closed');
      };
    }

    function connectControl() {
      console.log("connectControl")
      try {
        controlWs = new WebSocket(controlWsUrl);
      } catch (e) {
        console.error(e);
        return;
      }
      controlWs.onopen = ()=> {
        console.log("control open")
        connectVideo();
        getData();
      }
    }

  </script>

</head>
<body onload="initVideo()">
<button type="button" onclick="connectControl()">play</button>
<video width="100%" height="100%" autoplay>

</video>



</body>
</html>
